import java.util.Scanner;

public class HihoCoder1272 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int num = in.nextInt();
		for (; num > 0; num--) {
			int M = in.nextInt();
			double[] money = new double[M];
			int[] fun = new int[M];
			for (int i = 0; i < M; i++) {
				money[i] = in.nextDouble();
				fun[i] = in.nextInt();
			}
			handle(M, money, fun);
		}
	}

	private static void handle(int m, double[] money, int[] fun) {
		int funMax = 0;
		double moneyMax = 0;
		for (int i = 0; i < m; i++) {
					if (money[i]  % 5 == 0) {
						funMax = funMax > fun[i]?funMax : fun[i] ;
						moneyMax = moneyMax > money[i]? moneyMax:money[i] ;
					}
		}
		for (int i = 0; i < m; i++) {
			for (int j = i + 1; j < m; j++) {
					if ((money[i] + money[j]) % 5 == 0) {
						funMax = funMax > fun[i] + fun[j]  ? funMax : fun[i] + fun[j] ;
						moneyMax = moneyMax > money[i]+money[j]? moneyMax:money[i]+money[j] ;
					}

			}
		}
		for (int i = 0; i < m; i++) {
			for (int j = i + 1; j < m; j++) {
				for (int z = j + 1; z < m; z++) {
					if ((money[i] + money[j] + money[z]) % 5 == 0) {
						funMax = funMax > fun[i] + fun[j] + fun[z] ? funMax : fun[i] + fun[j] + fun[z];
						moneyMax = moneyMax > money[i] + money[j] + money[z] ? moneyMax
								: money[i] + money[j] + money[z];
					}
				}
			}
		}
		System.out.println(funMax);
	}
}
